#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

int main() {
	int listener = socket(AF_INET, SOCK_STREAM, 0);
	if (listener < 0) {
		perror("socket");
		exit(errno);
	}
	
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(2345);
	addr.sin_addr.s_addr = INADDR_ANY;
	if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("bind");
		exit(errno);
	}
	
	char buf[1024];
	printf("Server started.\n");
	listen(listener, 1);
	while (1) {
		int sock = accept(listener, NULL, NULL);
		if (sock < 0) {
			perror("accept");
			exit(errno);	
		}
		printf("accept\n");
		while (1) {
			int bytes_read = recv(sock, buf, 1024, 0);
			printf("Server: %s\n", buf);
			if (bytes_read <= 0) break;
			send(sock, buf, bytes_read, 0);
		}
		close(sock);
	}
	close(listener);
	return 0;
}
